<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import $api from '@/api/api'
import { Search, Edit, Plus, Delete, InfoFilled } from '@element-plus/icons-vue'

// 搜索表单数据
const searchForm = reactive({
  page: 1,
  pageSize: 10,
  author: '',
  ISBN: '',
  publisher: '',
  bname: '',
  bookStatus: ''
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 控制对话框显示
const dialogVisible = ref(false)
const dialogType = ref('') // add/edit
const dialogTitle = ref('')
const formLoading = ref(false)

// 表单数据
const bookForm = reactive({
  id: '',
  isbn: '',
  bname: '',
  author: '',
  publisher: '',
  introduction: '',
  pubDate: '',
  clcNum: '',
  bookStatus: 1,
  bookCopies: []
})

// 副本表单
const copyForm = reactive({
  barCode: '',
  place: '',
  status: 1
})

// 重置表单
const resetForm = () => {
  Object.assign(bookForm, {
    id: '',
    isbn: '',
    bname: '',
    author: '',
    publisher: '',
    introduction: '',
    pubDate: '',
    clcNum: '',
    bookStatus: 1,
    bookCopies: []
  })
}

// 获取图书列表
const fetchBooks = async () => {
  loading.value = true
  try {
    const res = await $api.getBookList(searchForm)
    if (res.code === 1) {
      tableData.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取图书列表失败')
    }
  } catch (error) {
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  searchForm.page = page
  fetchBooks()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  searchForm.pageSize = size
  searchForm.page = 1
  fetchBooks()
}

// 处理搜索
const handleSearch = () => {
  searchForm.page = 1
  fetchBooks()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    page: 1,
    pageSize: 10,
    author: '',
    ISBN: '',
    publisher: '',
    bname: '',
    bookStatus: ''
  })
  handleSearch()
}

// 打开新增对话框
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新书入库'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑图书'
  formLoading.value = true
  try {
    const res = await $api.getBookById(row.id)
    if (res.code === 1) {
      Object.assign(bookForm, res.data)
    } else {
      ElMessage.error(res.msg || '获取图书详情失败')
    }
  } catch (error) {
    ElMessage.error('获取图书详情失败')
  } finally {
    formLoading.value = false
  }
  dialogVisible.value = true
}

// 添加副本
const addCopy = () => {
  if (!copyForm.barCode || !copyForm.place) {
    ElMessage.warning('请填写完整的副本信息')
    return
  }
  bookForm.bookCopies.push({
    ...copyForm,
    status: 1
  })
  Object.assign(copyForm, {
    barCode: '',
    place: '',
    status: 1
  })
}

// 删除副本
const removeCopy = (index) => {
  bookForm.bookCopies.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  formLoading.value = true
  try {
    const api = dialogType.value === 'add' ? $api.addBook : $api.editBook
    const res = await api(bookForm)
    if (res.code === 1) {
      ElMessage.success(dialogType.value === 'add' ? '新书入库成功' : '编辑成功')
      dialogVisible.value = false
      fetchBooks()
    } else {
      ElMessage.error(res.msg || (dialogType.value === 'add' ? '新书入库失败' : '编辑失败'))
    }
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '新书入库失败' : '编辑失败')
  } finally {
    formLoading.value = false
  }
}

// 报废副本
const handleDeleteCopy = async (barCode) => {
  try {
    await ElMessageBox.confirm('确定要报废该副本吗？', '提示', {
      type: 'warning'
    })
    const res = await $api.deleteBookcopy(barCode)
    if (res.code === 1) {
      ElMessage.success('报废成功')
      fetchBooks()
    } else {
      ElMessage.error(res.msg || '报废失败')
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('报废失败')
  }
}

// 下架图书
const handleDeleteBook = async (id) => {
  try {
    await ElMessageBox.confirm('确定要下架该图书吗？这将删除所有副本！', '警告', {
      type: 'warning'
    })
    const res = await $api.deleteBook(id)
    if (res.code === 1) {
      ElMessage.success('下架成功')
      fetchBooks()
    } else {
      ElMessage.error(res.msg || '下架失败')
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('下架失败')
  }
}

onMounted(() => {
  fetchBooks()
})
</script>

<template>
  <div class="book-manage-page">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <div class="search-header">
        <h2>图书管理</h2>
        <el-button type="primary" @click="handleAdd" :icon="Plus">新书入库</el-button>
      </div>
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="书名">
          <el-input v-model="searchForm.bname" placeholder="请输入书名" clearable />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchForm.author" placeholder="请输入作者" clearable />
        </el-form-item>
        <el-form-item label="ISBN">
          <el-input v-model="searchForm.ISBN" placeholder="请输入ISBN" clearable />
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="searchForm.publisher" placeholder="请输入出版社" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.bookStatus" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图书列表 -->
    <el-card class="book-list-card" shadow="hover">
      <el-table
          :data="tableData"
          v-loading="loading"
          border
          stripe
          style="width: 100%"
          class="custom-table"
          empty-text="暂无图书数据"
      >
        <el-table-column prop="bname" label="书名" min-width="150" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" min-width="120" show-overflow-tooltip />
        <el-table-column prop="isbn" label="ISBN" min-width="120" show-overflow-tooltip />
        <el-table-column prop="publisher" label="出版社" min-width="120" show-overflow-tooltip />
        <el-table-column prop="clcNum" label="分类号" width="100" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.bookStatus === 1 ? 'success' : 'info'">
              {{ row.bookStatus === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="副本数" width="80">
          <template #default="{ row }">
            {{ row.bookCopies?.length || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDeleteBook(row.id)">
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!loading && tableData.length === 0" class="empty-tip">
        <img src="/src/assets/images/404.png" alt="empty" />
        <div>暂无图书数据</div>
      </div>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            layout="total, sizes, prev, pager, next, jumper"
            background
        />
      </div>
    </el-card>

    <!-- 编辑/新增对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="70%"
        class="custom-dialog"
        :close-on-click-modal="false"
    >
      <div v-loading="formLoading">
        <el-form :model="bookForm" label-width="100px" class="custom-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="ISBN">
                <el-input v-model="bookForm.isbn" placeholder="请输入ISBN" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="书名">
                <el-input v-model="bookForm.bname" placeholder="请输入书名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作者">
                <el-input v-model="bookForm.author" placeholder="请输入作者" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出版社">
                <el-input v-model="bookForm.publisher" placeholder="请输入出版社" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出版日期">
                <el-date-picker v-model="bookForm.pubDate" type="date" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分类号">
                <el-input v-model="bookForm.clcNum" placeholder="请输入分类号" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="简介">
                <el-input v-model="bookForm.introduction" type="textarea" rows="3" placeholder="请输入简介" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 副本管理 -->
          <div class="copies-section">
            <div class="copies-header">
              <h3>副本管理</h3>
              <div class="copy-form">
                <el-input v-model="copyForm.barCode" placeholder="条形码" style="width: 200px" />
                <el-input v-model="copyForm.place" placeholder="存放位置" style="width: 200px" />
                <el-button type="primary" @click="addCopy">添加副本</el-button>
              </div>
            </div>

            <el-table :data="bookForm.bookCopies" border stripe class="copies-table custom-table" empty-text="暂无副本">
              <el-table-column prop="barCode" label="条形码" />
              <el-table-column prop="place" label="存放位置" />
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <!-- <el-tag :type="row.status === 1 ? 'success' : row.status === 0 ? 'warning' : 'danger'"> -->
                    <!-- {{ row.status === 1 ? '可借' : row.status === 0 ? '借出' : '注销' }} -->
                      <el-tag :type="row.status === 1 ? 'success' : 'warning'">
                      {{ row.status === 1 ? '可借' : '不可借' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="{ row, $index }">
                  <el-button
                      type="danger"
                      link
                      :icon="Delete"
                      @click="dialogType === 'add' ? removeCopy($index) : handleDeleteCopy(row.barCode)"
                  >
                    {{ dialogType === 'add' ? '删除' : '报废' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="bookForm.bookCopies.length === 0" class="empty-tip" style="padding: 20px 0 0 0;">
              <div>暂无副本</div>
            </div>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.book-manage-page {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(120deg, #e4ecfb 0%, #f5f7fa 100%);
  font-family: 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 18px;
  background: rgba(255, 255, 255, 0.97);
  box-shadow: 0 6px 32px 0 rgba(80, 120, 255, 0.13);
  backdrop-filter: blur(14px);
  border: 1.5px solid #e0e7ff;
  transition: box-shadow 0.3s, border 0.3s;
}
.search-card:hover {
  box-shadow: 0 10px 40px 0 rgba(80, 120, 255, 0.18);
  border: 1.5px solid #6e8efb;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.search-header h2 {
  margin: 0;
  font-size: 2em;
  color: #355cfc;
  letter-spacing: 1.5px;
  font-weight: 800;
  text-shadow: 0 2px 8px #e0e7ff;
}

.el-button[type="primary"] {
  background: linear-gradient(90deg, #355cfc 0%, #6e8efb 100%);
  border: none;
  color: #fff;
  font-weight: 700;
  border-radius: 24px;
  box-shadow: 0 2px 8px 0 rgba(80, 120, 255, 0.13);
  transition: transform 0.15s, box-shadow 0.2s;
  letter-spacing: 1px;
  padding: 0 22px;
  min-width: 90px;
}
.el-button[type="primary"]:hover {
  transform: translateY(-2px) scale(1.06);
  background: linear-gradient(90deg, #6e8efb 0%, #355cfc 100%);
  box-shadow: 0 6px 18px 0 rgba(80, 120, 255, 0.18);
}
.el-button.is-loading {
  opacity: 0.7;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 14px;
  padding: 10px 0;
}

.el-input, .el-select {
  border-radius: 12px;
  background: #f4f7ff;
  border: 1.5px solid #e0e7ff;
  transition: border 0.2s, box-shadow 0.2s;
  box-shadow: 0 1px 4px 0 rgba(80, 120, 255, 0.04);
}
.el-input:focus-within, .el-select:focus-within {
  border-color: #355cfc;
  box-shadow: 0 0 0 2px #e0e7ff;
}
.el-input__inner, .el-select__wrapper {
  background: #f4f7ff !important;
  border-radius: 12px !important;
  font-size: 1em;
  color: #222;
}
.el-input__inner::placeholder {
  color: #b0b3c6;
  opacity: 1;
}

.book-list-card {
  border-radius: 18px;
  background: rgba(255, 255, 255, 0.99);
  box-shadow: 0 6px 32px 0 rgba(80, 120, 255, 0.13);
  backdrop-filter: blur(14px);
  border: 1.5px solid #e0e7ff;
  margin-bottom: 24px;
  position: relative;
  min-height: 320px;
  transition: box-shadow 0.3s, border 0.3s;
}
.book-list-card:hover {
  box-shadow: 0 12px 48px 0 rgba(80, 120, 255, 0.18);
  border: 1.5px solid #6e8efb;
}

.custom-table .el-table__header th {
  background: linear-gradient(90deg, #e0e7ff 0%, #f5f7fa 100%);
  color: #355cfc;
  font-weight: 700;
  border-radius: 12px 12px 0 0;
  font-size: 1.05em;
}
.custom-table .el-table__row {
  transition: background 0.2s;
}
.custom-table .el-table__row:hover {
  background: #f0f5ff !important;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0 20px 0;
  color: #b0b3c6;
  font-size: 1.1em;
  animation: fadeIn 0.6s;
}
.empty-tip img {
  width: 120px;
  margin-bottom: 12px;
  opacity: 0.7;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: none; }
}

.pagination-container {
  margin-top: 28px;
  display: flex;
  justify-content: center;
}

.el-pagination {
  background: #f4f7ff;
  border-radius: 12px;
  padding: 10px 20px;
  box-shadow: 0 2px 8px 0 rgba(80, 120, 255, 0.06);
  font-weight: 500;
}

.copies-section {
  margin-top: 36px;
  border-top: 1.5px solid #e0e7ff;
  padding-top: 24px;
}

.copies-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.copies-header h3 {
  margin: 0;
  font-size: 1.25em;
  color: #355cfc;
  font-weight: 700;
  letter-spacing: 1px;
}

.copy-form {
  display: flex;
  gap: 12px;
  align-items: center;
}
.copy-form .el-input {
  min-width: 120px;
}

.copies-table {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

.el-dialog.custom-dialog {
  border-radius: 22px !important;
  box-shadow: 0 12px 48px 0 rgba(80, 120, 255, 0.18);
  background: rgba(255,255,255,0.99);
  border: 1.5px solid #e0e7ff;
  animation: fadeIn 0.4s;
}
.el-dialog__header {
  font-size: 1.25em;
  color: #355cfc;
  font-weight: 700;
  letter-spacing: 1px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.el-form-item__label {
  color: #355cfc;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.el-form-item.is-required .el-form-item__label:after {
  color: #f56c6c;
}

.el-input__inner {
  background: #f4f7ff !important;
  border-radius: 12px !important;
}

.el-tag {
  font-size: 0.98em;
  border-radius: 8px;
  padding: 0 10px;
  font-weight: 600;
}

/* 响应式布局 */
@media (max-width: 900px) {
  .search-form {
    flex-direction: column;
    gap: 10px;
  }
  .search-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  .book-list-card {
    min-height: 180px;
  }
  .copy-form {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
}
@media (max-width: 600px) {
  .book-manage-page {
    padding: 4px;
  }
  .search-header h2 {
    font-size: 1.1em;
  }
  .el-dialog.custom-dialog {
    width: 99vw !important;
    min-width: unset !important;
    padding: 0;
  }
  .el-dialog__body {
    padding: 8px !important;
  }
  .el-form-item__label {
    font-size: 0.98em;
  }
}
</style>
